<?php

namespace addons\shopro\controller\user;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\Bonus;
use app\admin\model\shopro\BonusLog;
use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\StorePerformance;
use app\admin\model\shopro\Transfer;
use app\admin\model\shopro\user\Real;
use app\common\library\Sms;
use addons\shopro\controller\Common;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
use app\admin\model\shopro\ThirdOauth;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

class User extends Common
{

    protected $noNeedLogin = ['smsRegister', 'accountLogin', 'smsLogin', 'resetPassword'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        \think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');        // 加载语言包
    }

    /**
     * 用户数据
     */
    public function data()
    {
        $user = auth_user();
        // 查询用户优惠券数量
        $data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();

        // 订单数量
        $orderNum = [];
        $orderNum['unpaid'] = OrderModel::where('user_id', $user->id)->unpaid()->count();
        $orderNum['nosend'] = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
        $orderNum['noget'] = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
        $orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
        $orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();

        $data['order_num'] = $orderNum;

        $this->success('用户数据', $data);
    }

    /**
     * 第三方授权信息
     */
    public function thirdOauth()
    {
        $user = auth_user();

        $provider = $this->request->param('provider', '');
        $platform = $this->request->param('platform', '');
        if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
            $this->error(__('Invalid parameters'));
        }
        $where = [
            'platform' => $platform,
            'user_id' => $user->id
        ];
        if ($provider !== '') {
            $where['provider'] = $provider;
        }
        $oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
        $this->success('', $oauth);
    }


    /**
     * 用户信息
     */
    public function profile()
    {
        //TODO @ldh: 1.账号被禁用 2.连表查group
        $user = auth_user(true);
        //$user->id=169;
        $user = UserModel::with(['parent_user', 'third_oauth'])->where('id', $user->id)->find();
        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);
        //新增 lina start
        //计算本月和上月业绩
        if(!empty($user)){
            $performance=Performance::where(["user_id"=>$user["id"]])
                ->whereTime("createtime","last month")
                ->field("sum(money) money")
                ->buildSql();
            $list = Performance::where(["user_id"=>$user["id"]])
                ->field("sum(money) money")
                ->whereTime("createtime","month")
                ->union([$performance], true)
                ->select();
            $user["lastMonthPerformance"]=$list[1]["money"]??0;//上月业绩
            $user["monthPerformance"]=$list[0]["money"]??0;//本月业绩
            $level=Agent::field("user_id,level,dividend_level_time")
                    ->with(["levelInfo"=>function($query){
                        $query->field("level,name");
                    }])->where(["user_id"=>$user["id"]])->find();//等级
            $user["level_name"]=$level["level_info"]["name"]??'游客';
            $commission_rules=$level["level_info"]["commission_rules"]??[];
            $user["level_rate"]=$commission_rules["commission_1"]??0;
            //门店奖励业绩
            $user["store_performance"]=0;
            if($user["is_store"]==1){
                $user["store_performance"]=StorePerformance::where(["user_id"=>$user["id"]])->sum("money");
            }
            //实名认证
            if(!empty($user["ID_number"])){
                $user["real"]=1;
            }else{
                $user["real"]=3;
                $real=Real::where(["user_id"=>$user["id"]])->find();
                if(!empty($real)){
                    $user["real"]=$real["status"];
                }
            }
            //董事分红
            $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
            $self_performance=0;
            $big_market=0;
            $small_market=0;
            $market=0;
            $user["is_dividend"]=false;
            $last_end_money=0;//上次结算时的金额
            //$user["id"]=92;
            if(isset($user["agent"]) && $user["agent"]["level"]==$configs["level"]){
                $user["is_dividend"]=true;
                $user_bonus=(new \app\admin\model\shopro\user\Bonus)->where(["user_id"=>$user["id"]])->order("createtime","desc")->find();
                $now_time=time();//当前时间
                $before_half_year_time=strtotime(date("Y-m-d",strtotime("-6 month")));//半年以前
                //判断获得资格时间和半年前的时间，如果获得资格早于半年前就以半年前为统计时间
                $start_time=$level["dividend_level_time"]<=$before_half_year_time?$before_half_year_time:$level["dividend_level_time"];
                //如果存在
                if(!empty($user_bonus)){
                    $last_end_time=strtotime(date("Y-m-d",strtotime($user_bonus["createtime"])));//上次结算时间
                    if($last_end_time>=$start_time){
                        $start_time=$last_end_time;
                        $last_end_money=$user_bonus["big_money"]??0;
                    }
                }
                $where["createtime"]=[">=",$start_time];
                $self_performance=(new Performance())->where(["user_id"=>$user["id"]])->where($where)->sum("money");
                $fist_child_ids=\app\common\model\User::where("parent_user_id",$user["id"])->column("id");//查找所有直属下级用户ID
                $child_performance_money_sum=0;//下级业绩总和
                if($fist_child_ids){
                    foreach ($fist_child_ids as $k=>$childId){
                        $child_performance_money=(new Performance())->where(["user_id"=>$childId])->where($where)->sum("money");
                        if($k==0){
                            $big_market=$child_performance_money;
                        }elseif ($big_market < $child_performance_money){
                            $big_market=$child_performance_money;
                        }
                        $child_performance_money_sum+=$child_performance_money;
                    }
                }
                $self_performance=$self_performance+$last_end_money;//自己所有下级半年内的历史业绩总和
                $small_market=$child_performance_money_sum-$big_market;//小市场业绩
            }
//            if(isset($user["agent"]) && $user["agent"]["level"]==$configs["level"]){
//                $user["is_dividend"]=true;
//                //董事分红
//                $now_time=time();//strtotime(date("Y-m-d",time()));
//                $user_bonus=(new \app\admin\model\shopro\user\Bonus)->where(["user_id"=>$user["id"]])->order("createtime","desc")->find();
//                if(!empty($user_bonus)){
//                    //之前已经分红--时间从上次分红时间推算
//                    $time=strtotime(date("Y-m-d",strtotime($user_bonus["createtime"])));
//                }else{
//                    $time=strtotime(date("Y-m-d",strtotime("-6 month")));
//                    $user["dividend_level_time"]=strtotime(date("Y-m-d",$level["dividend_level_time"]??$time));
//                    if($user["dividend_level_time"]<$time && !empty($user["dividend_level_time"])){
//                        //如果已经超过半年时间
//                        $time=$user["dividend_level_time"];
//                    }
//                }
//                $dividend_level_time=strtotime(date("Y-m-d",$level["dividend_level_time"]));
//                $time_self=strtotime(date("Y-m-d",strtotime("-6 month")));
//                if(empty($level["dividend_level_time"])){
//                    $dividend_level_time=$time_self;
//                }
//                if($dividend_level_time<$time){
//                    //如果已经超过半年时间
//                    $time_self=$level["dividend_level_time"];
//                }
//                $where_self["createtime"]=["between",[$time_self,$now_time]];
//                $where["createtime"]=["between",[$time,$now_time]];
//                $where_dividend["is_dividend"]=["=",1];
//                $order_ids=Performance::field("GROUP_CONCAT(DISTINCT order_id) money")
//                    ->where($where)
//                    ->where($where_dividend)
//                    ->buildSql();
//                $self_performance_data = Performance::field("sum(money) money")
//                    ->where(["user_id"=>$user["id"]])
//                    ->where($where_self)
//                    ->where($where_dividend)
//                    ->union([$order_ids], true)
//                    ->select();//所有
//                $self_performance=$self_performance_data[0]["money"]??0;
//                if($self_performance>0){
//                    $ids=$self_performance_data[1]["money"]??0;
//                    if(!empty($ids)){
//                        $parent_user_id=\app\common\model\User::where("parent_user_id",$user["id"])->column("id");//查找下级所有用户id
//                        $list = Performance::whereIn("user_id",$parent_user_id)
//                            ->field("sum(money) money,user_id")
//                            ->where($where)
//                            ->whereIn("order_id",$ids)
//                            ->group("user_id")
//                            ->select();
//                        if(!empty($list)){
//                            foreach ($list as $v){
//                                $big_market = max($big_market , $v['money']);
//                                $market+=$v["money"];
//                            }
//                            $small_market=bcsub($market,$big_market,2);//小市场业绩
//                        }
//                    }
//                }
//            }
            $user["self_performance"]=$self_performance;
            $user["big_market"]=bcadd($big_market,($user_bonus["big_money"]??0),2) ;//加上上次结算的业绩
            $user["small_market"]=$small_market;
            //计算收益
            $event="'money_payment_income','money_payment_cut_income','money_dividend'";//,'payment_goods_order_pay_income'
            $today_income = \app\admin\model\shopro\user\WalletLog::field("sum(amount) money")
                ->where(["user_id" => $user["id"],"type"=>"money"])
                ->whereTime("createtime","today")
                ->where("(event in (".$event.")) or (event in('money_payment_cut_payment') and amount>0) or (event='payment_goods_order_pay_income' and (amount>0 or (amount<0 and memo like '%订单退货%')))")
                ->buildSql();//今天
            $all_income = \app\admin\model\shopro\user\WalletLog::field("sum(amount) money")
                ->where(["user_id" => $user["id"],"type"=>"money"])
                ->where("(event in (".$event.")) or (event in('money_payment_cut_payment') and amount>0) or (event='payment_goods_order_pay_income' and (amount>0 or (amount<0 and memo like '%订单退货%')))")
                ->union([$today_income], true)
                ->select();//所有
            $user["all_income"]=$all_income[0]["money"]??0;
            $user["today_income"]=$all_income[1]["money"]??0;
            $performance_tip = ShoproConfig::getConfigs('shop.order.performance_tip', false);//业绩说明
            $user["performance_tip"]=$performance_tip;
        }
        //新增 lina end
        $this->success('个人详情', $user);
    }

    /**
     * 更新用户资料
     */
    public function update()
    {
        $user = auth_user();

        $params = $this->request->only(['avatar', 'nickname', 'gender']);
        $this->svalidate($params);

        $user->save($params);
        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        $this->success('更新成功', $user);
    }

    /**
     * 账号密码登录
     */
    public function accountLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['account', 'password']);
        $this->svalidate($params, '.accountLogin');

        $ret = $this->auth->login($params['account'], $params['password']);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '注册失败');
        }
    }

    /**
     * 短信验证码登陆
     */
    public function smsLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.smsLogin');
        if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = UserModel::getByMobile($params['mobile']);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }else {
            $this->error('该手机号暂未注册');
        }
        if (isset($ret) && $ret) {
            Sms::flush($params['mobile'], 'mobilelogin');
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '登录失败');
        }
    }

    /**
     * 短信验证码注册
     */
    public function smsRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }

        $params = $this->request->only(['mobile', 'code', 'password','nickname']);
        $this->svalidate($params, '.smsRegister');

        /*$ret = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }*/

        // 注册
        $userAuth = new UserAuth();
        $auth = $userAuth->register($params);
        set_token_in_header($auth->getToken());

        $this->success(__('Sign up successful'));
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $user = auth_user();

        $params = $this->request->only(['oldPassword', 'newPassword']);
        $this->svalidate($params, '.changePassword');

        $userAuth = new UserAuth();
        $userAuth->changePassword($params['newPassword'], $params['oldPassword']);

        $this->auth->direct($user->id);
        set_token_in_header($this->auth->getToken());

        $this->success(__('Change password successful'));
    }

    /**
     * 重置/忘记密码
     */
    public function resetPassword()
    {
        $params = $this->request->only(['mobile', 'code', 'password']);
        $this->svalidate($params, '.resetPassword');

        $ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->resetPassword($params);

        $this->success(__('Reset password successful'));
    }

    /**
     * 更换手机号
     */
    public function changeMobile()
    {
        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.changeMobile');

        $ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->changeMobile($params);

        $this->success('绑定成功');
    }

    /**
     * 修改用户名
     */
    public function changeUsername()
    {
        $user = auth_user(true);

        $params = $this->request->only(['username']);
        $this->svalidate($params, '.changeUsername');

        $userAuth = new UserAuth();
        $userAuth->changeUsername($params);

        $this->success('绑定成功');
    }

    /**
     * 更新小程序头像和昵称
     */
    public function updateMpUserInfo()
    {
        $user = auth_user(true);

        $params = $this->request->only(['avatar', 'nickname']);
        $this->svalidate($params, '.updateMpUserInfo');

        $user->save($params);

        $thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
            'provider' => 'wechat',
            'platform' => 'miniProgram'
        ])->find();
        $thirdOauth->save($params);
        $this->success('绑定成功');
    }



    /**
     * 登出
     */
    public function logout()
    {
        $userAuth = new UserAuth();
        $userAuth->logout();

        $this->success(__('Logout successful'));
    }


    /**
     * 用户注销
     */
    public function logoff()
    {
        $userAuth = new UserAuth();
        $userAuth->logoff();

        $this->success('注销成功');
    }

    //2023-11-17 新增 lina start
    /**
     * 转账
     * */
    public function transfer()
    {
        $data=[
            ['mobile', 'require|regex:/^1\d{10}$/', '手机号码不能为空|手机号码格式错误'],
            ['money', 'require', '金额不能为空'],
            ['password', 'require', '密码不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $user = auth_user();
        $receive_user=UserModel::where(["mobile"=>$params["mobile"]])->find();
        if(empty($receive_user)) $this->error('转账用户不存在，请核实信息再转账');
        $config = sheep_config('shop.recharge_withdraw.transfer');
        // 手续费
        $charge = bcmul($params["money"], ($config['charge_rate']/100), 2);
        $cut_money=bcadd($params["money"],$charge,2);//实际扣除金额
        if ($user["money"]< $cut_money) {
            $this->error('余额不足');
        }
        // && $user["payment_goods"]<0
        if (!empty($user["agent"])&& $user["agent"]["level"] >2) {
            //$this->error('货款为负，请将货款充正后，才能转账');
            $commission_rules=$user["agent"]["level_info"]["commission_rules"];
            if(empty($commission_rules)) $this->error('请检查会员等级');
            $pay_money=bcsub($user["money"],$cut_money,2);
            $pay_money=bcdiv($pay_money,($commission_rules["commission_1"]/100),2);
            //$pay_money=bcsub($user["payment_goods"],$pay_money,2);
            if($user["payment_goods"]<0){
                $pay_money=bcadd($pay_money,$user["payment_goods"],2);
            }else{
                $pay_money=bcsub($pay_money,$user["payment_goods"],2);
            }
            if($pay_money<=0) $this->error('余额不足');
        }
        if(md5(md5($params["password"]) . $user["salt"])!=$user["password"]){
            $this->error('密码错误');
        }
        Db::startTrans();
        try {
            // 添加提现记录
            $transfer = new Transfer();
            $transfer->user_id = $user["id"];
            $transfer->money = $cut_money;
            $transfer->charge_fee = $charge;
            $transfer->charge_rate = $config['charge_rate'];
            $transfer->order_no = get_sn($user["id"], 'T');
            $transfer->paid_fee =$params["money"] ;
            $transfer->receive_user_id = $receive_user["id"];
            $transfer->momo = "转账";
            $transfer->createtime = time();
            $transfer->save();
            //扣除用户余额
            WalletService::change($user["id"], 'money', -$cut_money, 'money_transfer', [
                'order_id' => $transfer->id,
                'order_sn' => $transfer->order_no,
                'order_type' => "money_transfer",
            ],'转账给'.$receive_user["nickname"],$receive_user["id"]);//."真实信息(".$params["name"].")"
            //转账用户增加余额
            WalletService::change($receive_user["id"], 'money',$params["money"], 'money_transfer', [
                'order_id' => $transfer->id,
                'order_sn' => $transfer->order_no,
                'order_type' => "money_transfer",
            ],'收到来自'.$user["nickname"].'的转账',$user["id"]);//."真实信息(".$user["name"].")"
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('转账成功');
        // 扣除用户余额
    }
    /**
     * 根据手机号查找用户
     * */
    public function getMobileUser()
    {
        if(!$this->request->param("mobile")) $this->error("请输入手机号");
        if (!$this->request->param("mobile") || !\think\Validate::regex($this->request->param("mobile"), "^1\d{10}$")) {
            $this->error(('手机号不正确'));
        }
        $receive_user=UserModel::field("id,nickname,mobile,username,name")->where(["mobile"=>$this->request->param("mobile")])->find();
        if (empty($receive_user)) $this->error("用户不存在");
        $this->success('成功',$receive_user);
    }

    /**
     * 实名认证
     * */
    public function real()
    {
        $data=[
            ['name', 'require', '姓名不能为空'],
            ['ID_number', 'require', '身份证号码不能为空'],
            ['ID_front', 'require', '请上传身份证正面'],
            ['ID_opposite', 'require', '请上传身份证反面'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $user = auth_user();
        if(!empty($user["ID_number"])) $this->error("您的账户已经实名认证通过");
        $transfer = new Real();
        $log=$transfer->where(["user_id"=>$user["id"]])->where(["status"=>0])->find();
        if(!empty($log)) $this->error("您已提交实名认证申请，请等待平台审核");
        Db::startTrans();
        try {
            // 添加提现记录
            $transfer->user_id = $user["id"];
            $transfer->name = $params["name"];
            $transfer->ID_number = $params["ID_number"];
            $transfer->ID_front = $params["ID_front"];
            $transfer->ID_opposite = $params["ID_opposite"];
            $transfer->createtime = time();
            $transfer->save();
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交实名认证成功');
        // 扣除用户余额
    }
    //2023-11-17 新增 lina end

    /**
     * 购买商品之前点击同意阅读须知
     * */
    public function payAfterNotice()
    {
        $user=$this->auth->getUser();
        if(empty($user->pay_after_notice)){
            $user->pay_after_notice=1;
            $user->save();
        }
        $this->success('成功');
    }
}
